// stores/user.ts
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { login as loginApi, register as registerApi, adminLogin as adminLoginApi } from '@/api/auth';
import type { User, LoginCredentials, RegisterData } from '@/types/user';

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(
    localStorage.getItem('userInfo') 
      ? JSON.parse(localStorage.getItem('userInfo') as string)
      : null
  );
  const token = ref<string>(localStorage.getItem('token') || '');
  const permissions = ref<string[]>([]);
  const roles = ref<string[]>([]);

  // Getter
  const isAuthenticated = computed(() => !!token.value);
  
  const hasPermission = (permission: string) => {
    // 管理员拥有所有权限
    if (user.value?.role === 'admin') {
      return true;
    }
    return permissions.value.includes(permission);
  };
  
  const hasAnyPermission = (perms: string[]) => {
    if (user.value?.role === 'admin') {
      return true;
    }
    return perms.some(permission => permissions.value.includes(permission));
  };
  
  const hasRole = (role: string | string[]) => {
    const userRole = user.value?.role;
    if (!userRole) return false;
    
    if (Array.isArray(role)) {
      return role.includes(userRole);
    }
    return userRole === role;
  };

  // Actions
  const login = async(data: LoginCredentials) => {
    const res = await loginApi(data);
    token.value = res.data.token;
    user.value = res.data.user;
    
    // 持久化
    localStorage.setItem('token', res.data.token);
    localStorage.setItem('userInfo', JSON.stringify(res.data.user));
    
    // 初始化权限数据
    await initUserPermissions();
    
    return res;
  };

  const adminLogin = async(data: LoginCredentials) => {
    const res = await adminLoginApi(data);
    token.value = res.data.token;
    user.value = res.data.user;
    
    // 持久化
    localStorage.setItem('token', res.data.token);
    localStorage.setItem('userInfo', JSON.stringify(res.data.user));
    
    // 初始化权限数据
    await initUserPermissions();
    
    return res;
  };

  const register = async(data: RegisterData) => {
    const res = await registerApi(data);
    token.value = res.data.token;
    user.value = res.data.user;
    
    // 持久化
    localStorage.setItem('token', res.data.token);
    localStorage.setItem('userInfo', JSON.stringify(res.data.user));
    
    // 初始化权限数据
    await initUserPermissions();
    
    return res;
  };

  const logout = () => {
    user.value = null;
    token.value = '';
    permissions.value = [];
    roles.value = [];
    
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
  };

  // 初始化用户权限
  const initUserPermissions = async() => {
    if (!user.value) return;
    
    // 根据用户角色设置权限
    switch (user.value.role) {
    case 'admin':
      permissions.value = [
        'article:create', 
        'article:edit', 
        'article:view', 
        'article:delete',
        'collection:view',
        'system:manage', 
        'content:manage', 
        'user:manage'
      ];
      roles.value = ['admin'];
      break;
    case 'user':
      permissions.value = [
        'article:create', 
        'article:edit', 
        'article:view',
        'collection:view'
      ];
      roles.value = ['user'];
      break;
    default:
      permissions.value = ['article:view'];
      roles.value = ['guest'];
    }
    
    // 如果有后端权限接口，可以在这里调用
    // const permissionRes = await getUserPermissionsApi()
    // permissions.value = permissionRes.data.permissions
    // roles.value = permissionRes.data.roles
  };

  // 初始化用户状态（应用启动时调用）
  const initUser = () => {
    if (token.value && user.value) {
      initUserPermissions();
    }
  };

  // 更新用户信息
  const updateUserInfo = (userInfo: Partial<User>) => {
    if (user.value) {
      user.value = { ...user.value, ...userInfo };
      localStorage.setItem('userInfo', JSON.stringify(user.value));
    }
  };

  // 检查是否有路由访问权限
  const hasRoutePermission = (routeMeta: any) => {
    if (!routeMeta) return true;
    
    // 检查权限
    if (routeMeta.permission && !hasPermission(routeMeta.permission)) {
      return false;
    }
    
    // 检查角色
    if (routeMeta.roles && !hasRole(routeMeta.roles)) {
      return false;
    }
    
    return true;
  };

  return {
    // State
    user,
    token,
    permissions,
    roles,
    
    // Getter
    isAuthenticated,
    hasPermission,
    hasAnyPermission,
    hasRole,
    
    // Actions
    login,
    adminLogin,
    register,
    logout,
    initUser,
    initUserPermissions,
    updateUserInfo,
    hasRoutePermission
  };
});